import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['font.weight'] = 'bold'
plt.rcParams['mathtext.fontset'] = 'stix'

def draw_bar(data):
    x = np.arange(9)  # the label locations
    width = 0.35  # the width of the bars
    offset = 1
    multiplier = 0

    fig, ax = plt.subplots(layout='constrained')

    # error_params1=dict(elinewidth=3,ecolor='crimson',capsize=4)#设置误差标记参数
    # error_params2=dict(elinewidth=3,ecolor='blueviolet',capsize=4)#设置误差标记参数
    colors = ['skyblue', 'royalblue']
    
    for i, (attribute, measurement) in enumerate(data.items()):
        offset = width * multiplier
        ax.bar(x + offset, 
                measurement['Data'], 
                width, 
                label=attribute,
                yerr=[(measurement['Lower Error']), (measurement['Upper Error'])],
                color=colors[i])
        multiplier += 1

    # Add some text for labels, title and custom x-axis tick labels, etc.
    ax.set_ylabel('DSC')
    ax.set_xticks(x + width, 
                  ['Heart', 'Liver', 'Hippocampus', 'Prostate', 'Lung',
                   'Pancreas', 'Hepatic Vessel', 'Spleen', 'Colon'], 
                  rotation=45)
    ax.legend(loc='upper right', ncols=2)
    ax.set_ylim(0, 1)

    ax.grid(which='major', alpha=0.3)

    plt.show()
    

if __name__ == '__main__':
    data = {
        'Scratch': {
            'Data': np.random.uniform(0, 1, 9).round(4).tolist(),
            'Upper Error': np.random.uniform(0, 0.02, 9).round(4).tolist(),
            'Lower Error': np.random.uniform(0, 0.02, 9).round(4).tolist(),
        },
        'GMIM': {
            'Data': np.random.uniform(0, 1, 9).round(4).tolist(),
            'Upper Error': np.random.uniform(0, 0.02, 9).round(4).tolist(),
            'Lower Error': np.random.uniform(0, 0.02, 9).round(4).tolist(),
        }
    }

    draw_bar(data)